package com.woniuxy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.woniuxy.dao.PermssionMapper;
import com.woniuxy.pojo.Permission;
import com.woniuxy.service.PermissionService;
import com.woniuxy.util.DataGridView;
import com.woniuxy.util.TreeNode;
import com.woniuxy.util.TreeNodeBuilder;
import com.woniuxy.vo.PermissionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermssionMapper permssionMapper;

    @Override
    public List<TreeNode> selectMenusByUid(int uid) {
        List<TreeNode> tree=new ArrayList<TreeNode>();
        List<Permission> permissions=permssionMapper.selectMenusByUid(uid);
        for (Permission p:permissions) {
            TreeNode treeNode=new TreeNode();
            //将数据库中的字段更换成layui中的属性名
            treeNode.setId(p.getId());
            treeNode.setPid(p.getPid());
            treeNode.setTitle(p.getName());
            treeNode.setIcon(p.getIcon());
            treeNode.setHref(p.getHref());
            treeNode.setSpread(p.getOpen()==1?true:false);
            //加入到list
            tree.add(treeNode);
        }
        return TreeNodeBuilder.build(tree,1);//这个是加入子菜单
    }

    @Override
    public DataGridView getPermissionListByPage(PermissionVo permissionVo) {
        Page page= PageHelper.startPage(permissionVo.getPage(),permissionVo.getLimit());
        List<Permission> permissions=permssionMapper.selectPermissionByProperty(permissionVo);
        DataGridView dataGridView=new DataGridView(page.getTotal(),permissions);//将页数和数据带回去，这个之后会在前端显示出来
        return dataGridView;
    }

    @Override
    public List<Permission> selectAllPermission() {
        return permssionMapper.selectAllPermissions();
    }

    @Override
    public Integer[] selectPerIdByRid(int rid) {
        List<Permission> permissions=permssionMapper.selectPermissionsByRid(rid);
        Integer[] permissionIds=new Integer[permissions.size()];
        for (int i=0;i<permissions.size();i++){
            Permission p=(Permission)permissions.get(i);//获得对象
            permissionIds[i]=p.getId();//得到id
        }
        return permissionIds;
    }

    @Override
    public void assignRight(int rid, Integer[] perids) {
        permssionMapper.deleteRolePermission(rid);
        if(perids!=null&&perids.length>0){
            for(Integer perid:perids){
                this.permssionMapper.insertRolePermission(rid,perid);
            }
        }
    }
}
